package com.tsunami.utils;

/**
 * @author lx
 * @date 2024/5/11 11:51
 */
public class NumUtil {
    private NumUtil() {
    }

    private static final String[] CHINESE_NUMBERS = {"零", "一", "二", "三", "四", "五", "六", "七", "八", "九"};
    private static final String[] CHINESE_UNITS = {"", "十", "百", "千", "万", "亿"};

    /**
     * 数字转中文数字，全数字读法 加单位
     *
     * @param num 数字
     * @return 带单位的中文数字
     */
    public static String numToChinese(int num) {
        if (num == 0) {
            return CHINESE_NUMBERS[0];
        }
        StringBuilder result = new StringBuilder();
        int unitIndex = 0;
        boolean needZero = false;
        while (num > 0 && unitIndex < CHINESE_UNITS.length) {
            int currentNumber = num % 10;
            if (currentNumber == 0) {
                needZero = true;
            } else {
                if (needZero) {
                    result.insert(0, CHINESE_NUMBERS[0]);
                    needZero = false;
                }
                result.insert(0, CHINESE_NUMBERS[currentNumber] + CHINESE_UNITS[unitIndex]);
            }
            unitIndex++;
            num /= 10;
        }
        return result.toString();
    }

    /**
     * 数字转中文数字 单数字读法
     *
     * @param num 数字
     * @return 不带单位的中文数字
     */
    public static String numToChineseNum(int num) {
        if (num == 0) {
            return CHINESE_NUMBERS[0];
        }
        StringBuilder result = new StringBuilder();
        while (num > 0) {
            int currentNumber = num % 10;
            result.insert(0, CHINESE_NUMBERS[currentNumber]);
            num /= 10;
        }
        return result.toString();
    }

}
